<!DOCTYPE html>
<html lang="{{ page.lang | default: site.lang | default: "en" }}">

  {%- include head.html -%}

  <body>

    {%- include header.html -%}

    <main class="page-content" aria-label="Content">
      <div class="wrapper">
        <div class="builds_container">
            <select name="product" id="product">
                <option value="initial">Select a product...</option>
            </select>
            <select name="version" id="version">
                <option value="initial">Select version...</option>
            </select>
            <select name="sha" id="sha">
                <option value="initial">Select commit...</option>
            </select>
            <input type="checkbox" name="viewall" id="viewall" checked>View all
            <br>
            <div class="info" style="white-space: pre-line"></div>
            <table class="builds_viewcontainer"></table>
        </div>
      </div>
    </main>

    {%- include footer.html -%}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.1/showdown.min.js"></script>

    <script>
        $.getJSON("https://raw.githubusercontent.com/dortania/build-repo/builds/config.json", function (data) {
            var parameters = new URLSearchParams(window.location.search);
            const converter = new showdown.Converter()

            let per_category = {}
            Object.keys(data).filter(key => !key.startsWith("_")).forEach(key => {
                console.log(data[key]["type"])
                if (per_category[data[key]["type"]] == undefined) {
                    per_category[data[key]["type"]] = $("<optgroup>")
                    per_category[data[key]["type"]].attr("label", data[key]["type"])
                }
                per_category[data[key]["type"]].append(new Option(key, key))
            })
            Object.keys(per_category).forEach(key => $("#product").append(per_category[key]))
            var handleViewContainer = function () {
                $(".builds_viewcontainer").empty();
                parameters.set("viewall", $("#viewall")[0].checked)
                console.log("updated")
                window.history.replaceState("object or string", "Title", window.location.pathname.split(/[?#]/)[0] + "?" + parameters.toString());
                if (!($("#viewall").is(":checked")) || !($("#sha").val() == "initial")) {
                    return;
                }
                if ($("#product").val() == "initial") {
                    $(".builds_viewcontainer").text("You must select a product to view all builds.");
                    return;
                }
                if ($("#version").val() == "initial") {
                    // List versions + shas.
                    let versions = []
                    data[$("#product").val()]["versions"].forEach((element, index) => {
                        if (versions.findIndex(x => x == element.version) === -1) {
                            versions.push(element.version);
                        }
                    });
                    versions.forEach(version => {
                        let thead = $("<th>");
                        thead.attr("colspan", 4);
                        thead.append("<strong>" + version + "</strong>")
                        $(".builds_viewcontainer").append(thead);
                        let shas = []
                        data[$("#product").val()]["versions"].forEach((v, index) => {
                            if (v.version == version) {
                                shas.push([v, index]);
                            }
                        });
                        shas.forEach((element, index) => {
                            let container_p = $("<tr>")
                            let entry = element[0]
                            let hash_link = $("<a>")
                            hash_link.attr("href", entry.commit.url);
                            hash_link.text(entry.commit.sha.substring(0, 7));
                            container_p.append($("<td>").append($("<code>").append(hash_link)))

                            let message_text = $("<td>")
                            message_text.attr("class", "msg-column")
                            message_text.text(entry.commit.message.split("\n")[0])
                            container_p.append(message_text)

                            if (entry.links.debug) {
                                container_p.append(" ");
                                let debug_link = $("<a>");
                                debug_link.attr("href", entry.links.debug);
                                debug_link.text("DEBUG");
                                container_p.append($("<td>").append(debug_link));
                            }
                            if (entry.links.release) {
                                container_p.append(" ");
                                let release_link = $("<a>");
                                release_link.attr("href", entry.links.release);
                                release_link.text("RELEASE");
                                container_p.append($("<td>").append(release_link));
                            }
                            $(".builds_viewcontainer").append(container_p)
                        })
                    })
                } else {
                    // Just shas.
                    let shas = []
                    data[$("#product").val()]["versions"].forEach((element, index) => {
                        if (element.version == $("#version").val()) {
                            shas.push([element, index]);
                        }
                    });
                    shas.forEach((element, index) => {
                        let container_p = $("<tr>")
                        let entry = element[0]
                        let hash_link = $("<a>")
                        hash_link.attr("href", entry.commit.url);
                        hash_link.text(entry.commit.sha.substring(0, 7));
                        container_p.append($("<td>").append($("<code>").append(hash_link)))

                        let message_text = $("<td>")
                        message_text.attr("class", "msg-column")
                        message_text.text(entry.commit.message.split("\n")[0])
                        container_p.append(message_text)

                        if (entry.links.debug) {
                            container_p.append(" ");
                            let debug_link = $("<a>");
                            debug_link.attr("href", entry.links.debug);
                            debug_link.text("DEBUG");
                            container_p.append($("<td>").append(debug_link));
                        }
                        if (entry.links.release) {
                            container_p.append(" ");
                            let release_link = $("<a>");
                            release_link.attr("href", entry.links.release);
                            release_link.text("RELEASE");
                            container_p.append($("<td>").append(release_link));
                        }
                        $(".builds_viewcontainer").append(container_p)
                    })
                }

            }
            var resetInfo = function () {
                console.log("resetInfo");
                $(".info").empty()
                if ($("#product").val() == "initial" || $("#version").val() == "initial" || $("#sha").val() == "initial") {
                    parameters.delete("sha");
                    handleViewContainer();
                    return;
                }
                let entry = data[$("#product").val()]["versions"][$("#sha").val()]
                $(".info").html(converter.makeHtml(entry["release"]["description"]))
                $(".info").append("<p><strong>Download Links:</strong></p>")
                if (entry.links.debug) {
                    let debug_link = $("<a>");
                    debug_link.attr("href", entry.links.debug);
                    debug_link.text("Download Debug");
                    $(".info").append($("<p>").append(debug_link))
                }
                if (entry.links.release) {
                    let release_link = $("<a>");
                    release_link.attr("href", entry.links.release);
                    release_link.text("Download Release");
                    $(".info").append($("<p>").append(release_link))
                }
                if (entry.extras) {
                    Object.keys(entry.extras).forEach(key => {
                        let extra_link = $("<a>");
                        extra_link.attr("href", entry.extras[key]);
                        extra_link.text("Download " + key);
                        $(".info").append($("<p>").append(extra_link))
                    })
                }
                let gh_release_link = $("<a>");
                gh_release_link.attr("href", entry.release.url);
                gh_release_link.text("View on GitHub Releases");
                $(".info").append("<br>");
                $(".info").append(gh_release_link)
                parameters.set("sha", $("#sha").find(":selected").text().split(" ")[0])
                handleViewContainer();
                //$(".info").text()
            }
            var resetSha = function () {
                console.log("resetSha");
                $("#sha")[0].options.length = 0;
                $("#sha")[0].add(new Option("Select commit...", "initial", true, true));
                if ($("#product").val() == "initial" || $("#version").val() == "initial") {
                    parameters.delete("version")
                    resetInfo();
                    return;
                }
                let shas = []
                data[$("#product").val()]["versions"].forEach((element, index) => {
                    if (element.version == $("#version").val()) {
                        shas.push([element, index]);
                    }
                });
                shas.forEach((element, index) => $("#sha")[0].add(new Option(element[0].commit.sha + (index == 0 ? " (latest)" : ""), element[1])))
                parameters.set("version", $("#version").val())
                resetInfo();
            }
            var resetVersion = function () {
                console.log("resetVersion");
                $("#version")[0].options.length = 0;
                $("#version")[0].add(new Option("Select version...", "initial", true, true));
                if ($("#product").val() == "initial") {
                    parameters.delete("product")
                    resetSha();
                    return;
                }
                let versions = []
                data[$("#product").val()]["versions"].forEach((element, index) => {
                    if (versions.findIndex(x => x == element.version) === -1) {
                        versions.push(element.version);
                    }
                });
                versions.forEach((element, index) => {
                    $("#version")[0].add(new Option(element, element));
                })
                parameters.set("product", $("#product").val())
                resetSha();
            }
            $("#product").change(resetVersion)
            $("#version").change(resetSha)
            $("#sha").change(resetInfo)
            $("#viewall").change(handleViewContainer)
            let handleParameter = function(value, key) {
                if (key == "viewall") {
                    $("#viewall")[0].checked = (value == "true")
                } else  if (key == "sha") {
                    Array.from($("#sha")[0].children).forEach(element => {
                        console.log(element.innerText)
                        if (element.innerText.includes(value)) {
                            console.log("yup")
                            $("#sha").val(element.value).change()
                            console.log("done")
                        } else {
                            console.log("nope")
                        }
                    })
                } else {
                    console.log(key);
                    //$("#" + key).val(value).change()
                $("#" + key).val(value).change()
                }
            }
            parameters.forEach((value, key) => {
                setTimeout(function() {handleParameter(value, key)}, 100)
            });
            
        })
    </script>
  </body>

</html>